import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import '../services/image_translate_service.dart';
import '../models/translate_response.dart';
import '../constants/app_colors.dart';

// 百度图片翻译支持的语言列表
const imageTranslateLanguages = [
  { 'key': 'auto', 'value': '自动检测' },
  { 'key': 'zh', 'value': '中文' },
  { 'key': 'en', 'value': '英语' },
  { 'key': 'jp', 'value': '日语' },
  { 'key': 'kor', 'value': '韩语' },
  { 'key': 'fra', 'value': '法语' },
  { 'key': 'de', 'value': '德语' },
  { 'key': 'spa', 'value': '西班牙语' },
  { 'key': 'ru', 'value': '俄语' },
  { 'key': 'it', 'value': '意大利语' },
  { 'key': 'pt', 'value': '葡萄牙语' },
];

// 重新设计的图片翻译页面
class ImageTranslateScreen extends StatefulWidget {
  final String? sourceLanguage;
  final String? targetLanguage;

  const ImageTranslateScreen({
    Key? key,
    this.sourceLanguage,
    this.targetLanguage,
  }) : super(key: key);

  @override
  State<ImageTranslateScreen> createState() => _ImageTranslateScreenState();
}

class _ImageTranslateScreenState extends State<ImageTranslateScreen>
    with WidgetsBindingObserver {
  final ImageTranslateService _translateService = ImageTranslateService();
  File? _capturedImage;
  File? _translatedImage;
  bool _isLoading = false;
  late String _sourceLanguage;
  late String _targetLanguage;
  bool _isCameraMode = true;
  String? _errorMessage;

  // 用于存储翻译结果中的文本内容
  Map<String, dynamic> _translationTexts = {
    'original': '',
    'translated': '',
    'items': <Map<String, String>>[],
  };

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    _sourceLanguage = 'auto';
    _targetLanguage = _getMatchedLanguageCode(widget.targetLanguage) ?? 'en';
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 应用生命周期变化时管理相机
  }

  // 拍照
  Future<void> _takePicture() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final ImagePicker picker = ImagePicker();
      final XFile? photo = await picker.pickImage(
        source: ImageSource.camera,
        maxWidth: 1200,
        maxHeight: 1200,
        imageQuality: 85,
      );

      if (photo != null) {
        setState(() {
          _capturedImage = File(photo.path);
          _translatedImage = null;
          _isCameraMode = false;
        });

        await _translateImage();
      }
    } catch (e) {
      setState(() {
        _errorMessage = '拍照失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 从相册选择图片
  Future<void> _pickImageFromGallery() async {
    try {
      setState(() {
        _isLoading = true;
        _errorMessage = null;
      });

      final ImagePicker picker = ImagePicker();
      final XFile? imageFile = await picker.pickImage(
        source: ImageSource.gallery,
        maxWidth: 1200,
        maxHeight: 1200,
        imageQuality: 85,
      );

      if (imageFile != null) {
        setState(() {
          _capturedImage = File(imageFile.path);
          _translatedImage = null;
          _isCameraMode = false;
        });

        await _translateImage();
      }
    } catch (e) {
      setState(() {
        _errorMessage = '选择图片失败: $e';
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 获取匹配的语言代码
  String? _getMatchedLanguageCode(String? code) {
    if (code == null) return null;
    final simpleCode = code.split('-')[0];
    for (var lang in imageTranslateLanguages) {
      if (lang['key'] == simpleCode) {
        return lang['key'] as String;
      }
    }
    return null;
  }

  // 翻译图片
  Future<void> _translateImage() async {
    if (_capturedImage == null) {
      setState(() {
        _errorMessage = '请先拍照或选择图片';
      });
      return;
    }

    setState(() {
      _isLoading = true;
      _errorMessage = null;
    });

    try {
      final ImageTranslateResponse response = await _translateService.translateImage(
        imageFile: _capturedImage!,
        sourceLanguage: _sourceLanguage,
        targetLanguage: _targetLanguage,
      );

      if (response.success) {
        setState(() {
          _translationTexts = {
            'original': response.result.sumSrc.isNotEmpty
                ? response.result.sumSrc
                : response.result.content.map((item) => item.src).join('\n'),
            'translated': response.result.sumDst.isNotEmpty
                ? response.result.sumDst
                : response.result.content.map((item) => item.dst).join('\n'),
            'items': response.result.content.map((item) => {
              'src': item.src,
              'dst': item.dst,
            }).toList(),
          };
        });

        if (response.result.pasteImg.isNotEmpty) {
          try {
            String base64String = response.result.pasteImg;
            if (base64String.contains('data:image')) {
              base64String = base64String.replaceFirst(RegExp(r'data:image/\w+;base64,'), '');
            }

            final bytes = base64Decode(base64String);
            final tempDir = await Directory.systemTemp.createTemp('translate_result');
            final File imageFile = File('${tempDir.path}/result.jpg');
            await imageFile.writeAsBytes(bytes);

            setState(() {
              _translatedImage = imageFile;
            });
          } catch (e) {
            setState(() {
              _translatedImage = _capturedImage;
              _errorMessage = '图片处理失败，显示原图: $e';
            });
          }
        } else {
          setState(() {
            _translatedImage = _capturedImage;
            _errorMessage = '翻译结果未包含图片数据，但可以查看文字对照';
          });
        }
      } else {
        setState(() {
          _errorMessage = '翻译失败: ${response.logId}';
          _translatedImage = _capturedImage;
        });
      }
    } catch (e) {
      setState(() {
        _errorMessage = '图片翻译出错: $e';
        _translatedImage = _capturedImage;
      });
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    if (_isCameraMode) {
      return _buildCameraView();
    } else {
      return _buildResultView();
    }
  }

  // 重新设计的拍照界面 - 统一风格
  Widget _buildCameraView() {
    return Scaffold(
      backgroundColor: AppColors.background, // 使用统一的背景色
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        automaticallyImplyLeading: false,
        title: Text(
          '拍照翻译',
          style: TextStyle(
            color: AppColors.textPrimary,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.close, color: AppColors.textPrimary),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
      body: Column(
        children: [
          // 语言选择器
          _buildLanguageSelector(),

          // 主内容区域
          Expanded(
            child: _buildCameraContent(),
          ),

          // 底部按钮 - 改为垂直排列
          _buildVerticalControls(),
        ],
      ),
    );
  }

  // 简化的语言选择器
  Widget _buildLanguageSelector() {
    return Container(
      margin: const EdgeInsets.all(16),
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 2),
          ),
        ],
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          _buildLanguageChip(_sourceLanguage, true),
          Container(
            margin: const EdgeInsets.symmetric(horizontal: 16),
            child: Icon(
              Icons.arrow_forward,
              color: AppColors.primary,
              size: 20,
            ),
          ),
          _buildLanguageChip(_targetLanguage, false),
        ],
      ),
    );
  }

  // 重新设计的语言选择按钮
  Widget _buildLanguageChip(String language, bool isSource) {
    return GestureDetector(
      onTap: () => _showLanguageSelector(context, isSource),
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
        decoration: BoxDecoration(
          color: AppColors.primary.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(20),
          border: Border.all(color: AppColors.primary.withValues(alpha: 0.3)),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              _getLanguageDisplayName(language),
              style: TextStyle(
                color: AppColors.primary,
                fontSize: 14,
                fontWeight: FontWeight.w600,
              ),
            ),
            const SizedBox(width: 6),
            Icon(
              Icons.keyboard_arrow_down,
              color: AppColors.primary,
              size: 16,
            ),
          ],
        ),
      ),
    );
  }

  // 简化的主内容区域
  Widget _buildCameraContent() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          // 相机图标
          Container(
            width: 120,
            height: 120,
            decoration: BoxDecoration(
              color: AppColors.primary.withValues(alpha: 0.1),
              shape: BoxShape.circle,
              border: Border.all(
                color: AppColors.primary.withValues(alpha: 0.3),
                width: 2,
              ),
            ),
            child: Icon(
              Icons.camera_alt,
              color: AppColors.primary,
              size: 60,
            ),
          ),

          const SizedBox(height: 32),

          // 标题
          Text(
            '拍照翻译',
            style: TextStyle(
              color: AppColors.textPrimary,
              fontSize: 28,
              fontWeight: FontWeight.bold,
            ),
          ),

          const SizedBox(height: 12),

          // 描述
          Text(
            '将相机对准需要翻译的文字\n或从相册选择图片',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: AppColors.textSecondary,
              fontSize: 16,
              height: 1.5,
            ),
          ),

          // 错误提示
          if (_errorMessage != null) ...[
            const SizedBox(height: 24),
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.red.withValues(alpha: 0.1),
                borderRadius: BorderRadius.circular(12),
                border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
              ),
              child: Row(
                children: [
                  Icon(Icons.error_outline, color: Colors.red, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      _errorMessage!,
                      style: TextStyle(color: Colors.red, fontSize: 14),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ],
      ),
    );
  }

  // 新的垂直按钮布局
  Widget _buildVerticalControls() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 拍照按钮
          _buildActionButton(
            icon: Icons.camera_alt,
            label: '拍照翻译',
            onTap: _takePicture,
            isPrimary: true,
          ),

          const SizedBox(height: 12),

          // 相册按钮
          _buildActionButton(
            icon: Icons.photo_library,
            label: '从相册选择',
            onTap: _pickImageFromGallery,
            isPrimary: false,
          ),
        ],
      ),
    );
  }

  // 统一的按钮组件
  Widget _buildActionButton({
    required IconData icon,
    required String label,
    required VoidCallback onTap,
    required bool isPrimary,
  }) {
    return GestureDetector(
      onTap: _isLoading ? null : onTap,
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.symmetric(vertical: 16),
        decoration: BoxDecoration(
          color: isPrimary ? AppColors.primary : Colors.transparent,
          borderRadius: BorderRadius.circular(12),
          border: isPrimary ? null : Border.all(color: AppColors.primary),
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              icon,
              color: isPrimary ? Colors.white : AppColors.primary,
              size: 24,
            ),
            const SizedBox(width: 12),
            Text(
              label,
              style: TextStyle(
                color: isPrimary ? Colors.white : AppColors.primary,
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 重新设计的结果页面
  Widget _buildResultView() {
    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () {
            setState(() {
              _isCameraMode = true;
            });
          },
        ),
        title: Text(
          '翻译结果',
          style: TextStyle(
            color: AppColors.textPrimary,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        actions: [
          IconButton(
            icon: Icon(Icons.close, color: AppColors.textPrimary),
            onPressed: () => Navigator.pop(context),
          ),
        ],
      ),
      body: Column(
        children: [
          // 图片显示区域
          Expanded(
            child: Container(
              margin: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.circular(16),
                boxShadow: [
                  BoxShadow(
                    color: Colors.black.withValues(alpha: 0.05),
                    blurRadius: 10,
                    offset: const Offset(0, 2),
                  ),
                ],
              ),
              child: Stack(
                children: [
                  if (_translatedImage != null)
                    ClipRRect(
                      borderRadius: BorderRadius.circular(16),
                      child: Image.file(
                        _translatedImage!,
                        width: double.infinity,
                        height: double.infinity,
                        fit: BoxFit.contain,
                      ),
                    ),
                  if (_isLoading) _buildLoadingOverlay(),
                  if (_errorMessage != null && !_isLoading) _buildErrorOverlay(),
                ],
              ),
            ),
          ),

          // 底部操作按钮 - 改为垂直排列
          _buildResultVerticalControls(),
        ],
      ),
    );
  }

  // 结果页面的垂直按钮布局
  Widget _buildResultVerticalControls() {
    return Container(
      padding: const EdgeInsets.all(24),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          // 文字对照按钮
          _buildActionButton(
            icon: Icons.compare_arrows,
            label: '查看文字对照',
            onTap: () => _showComparisonView(context),
            isPrimary: true,
          ),

          const SizedBox(height: 12),

          // 操作按钮行
          Row(
            children: [
              Expanded(
                child: _buildActionButton(
                  icon: Icons.refresh,
                  label: '重新拍摄',
                  onTap: () {
                    setState(() {
                      _isCameraMode = true;
                    });
                  },
                  isPrimary: false,
                ),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: _buildActionButton(
                  icon: Icons.save,
                  label: '保存图片',
                  onTap: () {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: const Text('图片已保存'),
                        backgroundColor: AppColors.success,
                      ),
                    );
                  },
                  isPrimary: false,
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  // 简化的加载提示
  Widget _buildLoadingOverlay() {
    return Container(
      decoration: BoxDecoration(
        color: Colors.white.withValues(alpha: 0.9),
        borderRadius: BorderRadius.circular(16),
      ),
      child: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            CircularProgressIndicator(
              color: AppColors.primary,
            ),
            const SizedBox(height: 16),
            Text(
              '正在翻译...',
              style: TextStyle(
                color: AppColors.textPrimary,
                fontSize: 16,
                fontWeight: FontWeight.w600,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 简化的错误提示
  Widget _buildErrorOverlay() {
    return Positioned(
      top: 16,
      left: 16,
      right: 16,
      child: Container(
        padding: const EdgeInsets.all(16),
        decoration: BoxDecoration(
          color: Colors.red.withValues(alpha: 0.1),
          borderRadius: BorderRadius.circular(12),
          border: Border.all(color: Colors.red.withValues(alpha: 0.3)),
        ),
        child: Row(
          children: [
            Icon(Icons.error_outline, color: Colors.red, size: 20),
            const SizedBox(width: 8),
            Expanded(
              child: Text(
                _errorMessage!,
                style: TextStyle(color: Colors.red, fontSize: 14),
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 获取语言显示名称
  String _getLanguageDisplayName(String code) {
    for (var lang in imageTranslateLanguages) {
      if (lang['key'] == code) {
        return lang['value'] as String;
      }
    }
    return code;
  }

  // 显示语言选择器
  void _showLanguageSelector(BuildContext context, bool isSource) {
    showModalBottomSheet(
      context: context,
      backgroundColor: Colors.transparent,
      isScrollControlled: true,
      builder: (context) {
        return Container(
          height: MediaQuery.of(context).size.height * 0.7,
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.vertical(top: Radius.circular(24)),
          ),
          child: Column(
            children: [
              Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: AppColors.primary.withValues(alpha: 0.05),
                  borderRadius: const BorderRadius.vertical(top: Radius.circular(24)),
                ),
                child: Column(
                  children: [
                    Container(
                      width: 40,
                      height: 4,
                      decoration: BoxDecoration(
                        color: Colors.grey.shade300,
                        borderRadius: BorderRadius.circular(2),
                      ),
                    ),
                    const SizedBox(height: 16),
                    Text(
                      isSource ? '选择源语言' : '选择目标语言',
                      style: TextStyle(
                        color: AppColors.textPrimary,
                        fontSize: 20,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
              Expanded(
                child: ListView.builder(
                  padding: const EdgeInsets.symmetric(vertical: 8),
                  itemCount: imageTranslateLanguages.length,
                  itemBuilder: (context, index) {
                    final lang = imageTranslateLanguages[index];
                    final value = lang['key'] as String;
                    final isSelected = isSource
                        ? _sourceLanguage == value
                        : _targetLanguage == value;

                    if (!isSource && value == 'auto') return const SizedBox.shrink();

                    return Container(
                      margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                      decoration: BoxDecoration(
                        color: isSelected ? AppColors.primary.withValues(alpha: 0.1) : null,
                        borderRadius: BorderRadius.circular(12),
                        border: isSelected
                            ? Border.all(color: AppColors.primary.withValues(alpha: 0.3))
                            : null,
                      ),
                      child: ListTile(
                        title: Text(
                          lang['value'] as String,
                          style: TextStyle(
                            color: isSelected ? AppColors.primary : AppColors.textPrimary,
                            fontWeight: isSelected ? FontWeight.w600 : FontWeight.w500,
                            fontSize: 16,
                          ),
                        ),
                        trailing: isSelected
                            ? Icon(Icons.check_circle, color: AppColors.primary)
                            : null,
                        onTap: () {
                          setState(() {
                            if (isSource) {
                              _sourceLanguage = value;
                            } else {
                              _targetLanguage = value;
                            }
                          });
                          Navigator.pop(context);
                        },
                      ),
                    );
                  },
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  // 显示对照视图
  void _showComparisonView(BuildContext context) {
    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder: (context, animation, secondaryAnimation) => _buildComparisonView(),
        transitionsBuilder: (context, animation, secondaryAnimation, child) {
          return SlideTransition(
            position: animation.drive(
              Tween(begin: const Offset(1.0, 0.0), end: Offset.zero)
                  .chain(CurveTween(curve: Curves.easeInOut)),
            ),
            child: child,
          );
        },
      ),
    );
  }

  // 构建对照视图
  Widget _buildComparisonView() {
    final List<String> originalTexts = _translationTexts['original']
        .toString()
        .split('\n')
        .where((text) => text.trim().isNotEmpty)
        .toList();

    final List<String> translatedTexts = _translationTexts['translated']
        .toString()
        .split('\n')
        .where((text) => text.trim().isNotEmpty)
        .toList();

    final List<Map<String, String>> comparisonItems =
        ((_translationTexts['items'] ?? []) as List)
            .map<Map<String, String>>((item) => {
                  'original': item['src'] ?? '',
                  'translated': item['dst'] ?? '',
                })
            .toList();

    // 如果没有详细对照项，则从原文和译文中创建
    if (comparisonItems.isEmpty && originalTexts.isNotEmpty && translatedTexts.isNotEmpty) {
      final int minLength = originalTexts.length < translatedTexts.length
          ? originalTexts.length
          : translatedTexts.length;

      for (int i = 0; i < minLength; i++) {
        comparisonItems.add({
          'original': originalTexts[i],
          'translated': translatedTexts[i],
        });
      }
    }

    // 如果仍然没有内容，则显示空状态
    if (originalTexts.isEmpty && translatedTexts.isEmpty && comparisonItems.isEmpty) {
      return Scaffold(
        backgroundColor: AppColors.background,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          leading: IconButton(
            icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
            onPressed: () => Navigator.pop(context),
          ),
          title: Text(
            '文字对照',
            style: TextStyle(
              color: AppColors.textPrimary,
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                width: 120,
                height: 120,
                decoration: BoxDecoration(
                  color: AppColors.primary.withValues(alpha: 0.1),
                  shape: BoxShape.circle,
                ),
                child: Icon(
                  Icons.translate_rounded,
                  size: 60,
                  color: AppColors.primary.withValues(alpha: 0.6),
                ),
              ),
              const SizedBox(height: 24),
              Text(
                '暂无翻译内容',
                style: TextStyle(
                  fontSize: 20,
                  fontWeight: FontWeight.w600,
                  color: AppColors.textPrimary,
                ),
              ),
              const SizedBox(height: 12),
              Text(
                '请重新拍照或选择图片进行翻译',
                style: TextStyle(
                  fontSize: 16,
                  color: AppColors.textSecondary,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return Scaffold(
      backgroundColor: AppColors.background,
      appBar: AppBar(
        backgroundColor: Colors.white,
        elevation: 0,
        leading: IconButton(
          icon: Icon(Icons.arrow_back, color: AppColors.textPrimary),
          onPressed: () => Navigator.pop(context),
        ),
        title: Text(
          '文字对照',
          style: TextStyle(
            color: AppColors.textPrimary,
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
      ),
      body: SingleChildScrollView(
        padding: const EdgeInsets.all(20),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            // 摘要卡片
            if (originalTexts.isNotEmpty || translatedTexts.isNotEmpty) ...[
              _buildSummaryCard('原文摘要', originalTexts, AppColors.primary),
              const SizedBox(height: 16),
              _buildSummaryCard('译文摘要', translatedTexts, AppColors.success),
              const SizedBox(height: 32),
            ],

            // 详细对照
            if (comparisonItems.isNotEmpty) ...[
              Row(
                children: [
                  Icon(Icons.compare_arrows, color: AppColors.primary, size: 24),
                  const SizedBox(width: 8),
                  Text(
                    '详细对照',
                    style: TextStyle(
                      fontSize: 20,
                      fontWeight: FontWeight.bold,
                      color: AppColors.textPrimary,
                    ),
                  ),
                ],
              ),
              const SizedBox(height: 16),
              ...comparisonItems.map((item) => _buildComparisonCard(item)),
            ],
          ],
        ),
      ),
    );
  }

  Widget _buildSummaryCard(String title, List<String> items, Color color) {
    if (items.isEmpty) return const SizedBox.shrink();

    return Container(
      padding: const EdgeInsets.all(20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Container(
                width: 4,
                height: 20,
                decoration: BoxDecoration(
                  color: color,
                  borderRadius: BorderRadius.circular(2),
                ),
              ),
              const SizedBox(width: 12),
              Text(
                title,
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: AppColors.textPrimary,
                ),
              ),
            ],
          ),
          const SizedBox(height: 16),
          ...items.map((item) => Padding(
                padding: const EdgeInsets.only(bottom: 8),
                child: Text(
                  item,
                  style: TextStyle(
                    fontSize: 16,
                    height: 1.5,
                    color: AppColors.textPrimary,
                  ),
                ),
              )),
        ],
      ),
    );
  }

  Widget _buildComparisonCard(Map<String, String> item) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(16),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 10,
            offset: const Offset(0, 4),
          ),
        ],
      ),
      child: Column(
        children: [
          Container(
            padding: const EdgeInsets.all(20),
            decoration: BoxDecoration(
              color: AppColors.primary.withValues(alpha: 0.05),
              borderRadius: const BorderRadius.vertical(top: Radius.circular(16)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Row(
                  children: [
                    Icon(Icons.text_fields, color: AppColors.primary, size: 18),
                    SizedBox(width: 8),
                    Text(
                      '原文',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: AppColors.primary,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8),
                Text(
                  item['original']!,
                  style: TextStyle(
                    fontSize: 16,
                    height: 1.5,
                    color: AppColors.textPrimary,
                  ),
                ),
              ],
            ),
          ),
          Container(
            padding: const EdgeInsets.all(20),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Row(
                  children: [
                    Icon(Icons.translate, color: AppColors.success, size: 18),
                    SizedBox(width: 8),
                    Text(
                      '译文',
                      style: TextStyle(
                        fontSize: 14,
                        fontWeight: FontWeight.w600,
                        color: AppColors.success,
                      ),
                    ),
                  ],
                ),
                SizedBox(height: 8),
                Text(
                  item['translated']!,
                  style: const TextStyle(
                    fontSize: 16,
                    height: 1.5,
                    color: AppColors.textPrimary,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}